package action;

import inc.CommonFunction;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lottery.BankAccountConfig;
import lottery.BankDeposit;
import lottery.BetRecord;
import lottery.BetWay;
import lottery.BetwayManage;
import lottery.PayReward;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import code.lewdy.app.communication.Alert;
import code.lewdy.app.communication.Message;
import code.lewdy.app.notice.Notice;
import code.lewdy.app.user.AccountRecord;
import code.lewdy.app.user.WithdrawRecord;
import code.lewdy.db.Database;
import code.lewdy.db.HibernateTemple;
import code.lewdy.db.JdbcTemple;
import code.lewdy.db.JdbcUtil;
import code.lewdy.lottery.LotteryService;
import code.lewdy.lottery.OpenRewardNumber;
import code.lewdy.lottery.UnionBuyRecord;
import code.lewdy.lottery.UnionBuySet;
import code.lewdy.time.TimeHelper;
import code.lewdy.util.DataType;
import code.lewdy.util.RandomUtil;
import code.lewdy.web.PassportUtil;
import code.lewdy.web.response.ExtResponse;

import com.lt.member.Member;
import com.lt.member.MemberConfig;
import com.opensymphony.xwork2.ActionSupport;

public class SaveAction extends ActionSupport implements ServletRequestAware,
		ServletResponseAware {

	private HttpServletRequest req;
	private HttpServletResponse resp;
	private CommonFunction fun = new CommonFunction();
	JdbcUtil jdbc = new JdbcUtil(Database.TYPE_SQLSERVER);
	PayReward pay = new PayReward();
	private String ext1; // 扩展字段1
	private String ext2; // 扩展字段1
	private String classPath;
	private Notice notice;
	private Message message;
	private BetWay betway;
	private BetwayManage betwayMg;
	private BankDeposit bankdp;
	private OpenRewardNumber openNumber;
	private BetRecord br;
	private WithdrawRecord wr;
	private BankAccountConfig rechargeBank; // 充值账号
	private UnionBuySet unionSet; // 合买设置
	private UnionBuyRecord unionRecord; // 合买记录
	private double reward; // 奖金

	/**
	 * 保存实体
	 * 
	 * @return
	 * @author liuding,2012-5-17
	 */
	public String save() {
		Date date = new Date();
		if (Notice.class.getName().equals(classPath)) {
			notice.setCreateDate(date);
			notice.setOwnerId(new Long(PassportUtil.getUserId(req)));
			notice
					.setOwnerName(PassportUtil.getUserName(req) != null ? PassportUtil
							.getUserName(req)
							: "测试用户");
			HibernateTemple.save(notice);
		} else if (BetwayManage.class.getName().equals(classPath)) {
			HibernateTemple.save(betwayMg);
		} else if (BankDeposit.class.getName().equals(classPath)) {
			HibernateTemple.save(bankdp);
		} else if (OpenRewardNumber.class.getName().equals(classPath)) {
			HibernateTemple.save(openNumber);
			pay.payReward(openNumber);
			// 更新投注记录中的开奖号码
			int updater = JdbcTemple
					.executeUpdate("update BetRecord set openRewardNumber='"
							+ openNumber.getNumber() + "' where numberId='"
							+ openNumber.getPeriodNo() + "' and lotteryId="
							+ openNumber.getLotteryId());
			System.out.println("添加开奖号码更新投注记录：" + updater);
		} else if (BetRecord.class.getName().equals(classPath)) {
			double totalAmount = br.getSingleAmount() * br.getCount();
			if (totalAmount <= 0) {
				ExtResponse.error(resp, "操作失败：投注总额必须大于0！", DataType.XML);
				return null;
			}
			Member m = (Member) HibernateTemple.load(Member.class, Integer
					.parseInt(br.getOwnerId() + ""));
			if ((m.getBalance() - totalAmount) < 0) {
				// 余额不够，投注失败
				ExtResponse.error(resp, "余额不足，操作失败！", DataType.XML);
				return null;
			}
			//BetWay bet = (BetWay) HibernateTemple.load(BetWay.class, br.getBetId());
			String number = br.getNumber();
			String betName = br.getBetName();
			br.setBetName(betName);
			if(betName.indexOf("单式")>0 && LotteryService.hasRepeat(number)){
				// 作弊
				ExtResponse.error(resp, "投注中含重复号码!", DataType.XML);
				return null;
			}
			m.setBalance(m.getBalance() - totalAmount);
			HibernateTemple.update(m); // 更新账户余额
			br.setCreateDate(date);
			br.setOrderId(RandomUtil.getRandomString(18));
			br.setOwnerName(m.getUsername());
			HibernateTemple.save(br); // 保存投注记录
			// 创建账变记录
			new AccountRecord()
					.insert(m, br.getOrderId(),
							AccountRecord.GROUP_LOTTERY_AFTER_BET,
							-totalAmount, "投注追号");
			ExtResponse.ok(resp, "操作成功！", DataType.XML);

		} else if (WithdrawRecord.class.getName().equals(classPath)) {
			if (wr == null)
				return null;
			Date date1 = new Date();
			SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
			MemberConfig mcfg = (MemberConfig) HibernateTemple.load(
					MemberConfig.class, 1);
			String configDate1 = sdf1.format(date1);
			String configDate2 = sdf1.format(date1);
			Calendar c = Calendar.getInstance();
			int hour = c.get(Calendar.HOUR_OF_DAY);
			int minute = c.get(Calendar.MINUTE);
			int second = c.get(Calendar.SECOND);
			int s = hour * 3600 + minute * 60 + second;

			configDate1 = configDate1 + " "
					+ TimeHelper.turnSecondToHHMMSS(mcfg.getDepositBeginTime());
			configDate2 = configDate2 + " "
					+ TimeHelper.turnSecondToHHMMSS(mcfg.getDepositEndTime());
			if(mcfg.getDepositMinAmount() > wr.getAmount()){
				ExtResponse.error(resp, "操作失败：提现金额不得小于"+mcfg.getDepositMinAmount()+"元!", DataType.XML);
				return null;
			}
			if(mcfg.getDepositMaxAmount() < wr.getAmount()){
				ExtResponse.error(resp, "操作失败：提现金额不得大于"+mcfg.getDepositMaxAmount()+"元!", DataType.XML);
				return null;
			}
			if (s > mcfg.getDepositEndTime() || s < mcfg.getDepositBeginTime()) {
				ExtResponse.error(resp, "操作失败：请在提现时间段时进行此操作!", DataType.XML);
				return null;
			}
			
			Member m = (Member) HibernateTemple.load(Member.class, Integer
					.parseInt("" + wr.getOwnerId()));
			if(m.getBankName()==null || m.getBankNo()==null
					|| m.getBankName().equals("") || m.getBankNo().equals("")){
				ExtResponse.error(resp, "操作失败：请先设置提现资料!", DataType.XML);
				return null;
			}
			// 时间段时提现次数
			long depositeCount = (Long) HibernateTemple
			.getUniqueResult("select count(*) from WithdrawRecord where ownerId="
					+ m.getId()
					+ " and CONVERT(varchar(50) , createDate, 120 )<='"
					+ configDate2 +"'"
					+ " and CONVERT(varchar(50) , createDate, 120 )>='"
					+ configDate1 +"'");
			if (depositeCount >= mcfg.getDepositMaxCount()) {
				ExtResponse.error(resp, "操作失败：今天提现次数已达限制!", DataType.XML);
				return null;
			}
			if (m.getSecurityPassword() != null
					&& ext1 != null
					&& m.getSecurityPassword()
							.equals(fun.encryptPassword(ext1))) {
				if (m.getBalance() < wr.getAmount()) {
					ExtResponse.error(resp, "操作失败：提现金额大于账户余额!", DataType.XML);
					return null;
				}
				wr.setCreateDate(date);
				HibernateTemple.save(wr);
				// 扣除账户中相应提现金额
				m.setBalance(m.getBalance() - wr.getAmount());
				HibernateTemple.update(m);
				new AccountRecord().insert(m, RandomUtil.getRandomString(18),
						AccountRecord.GROUP_USER_WITHDRAW, -wr.getAmount(),
						"申请提现");
				new Alert().save(m, "提现消息", "您提现" + wr.getAmount()
						+ "元正在等候处理，请稍后...");
				ExtResponse.ok(resp, "操作成功！", DataType.XML);
			} else {
				// 安全密码错误
				ExtResponse.error(resp, "安全密码验证错误！", DataType.XML);
			}
		} else if (BetWay.class.getName().equals(classPath)) {
			BetwayManage bm = new BetwayManage();
			Long betwayId = HibernateTemple.save(betway);
			bm.setBetwayId(Integer.parseInt("" + betwayId));
			bm.setBetwayName(betway.getName());
			bm.setLotteryId(betway.getLotteryId());
			bm.setLotteryName(betway.getLotteryName());
			HibernateTemple.save(bm);
		} else if (Message.class.getName().equals(classPath)) {
			if (message.getTypeId() == Message.TYPE_MSG_ONLINE) {
				// 站内信
				int receiverId = jdbc
						.getInt("select id from Member where username='"
								+ message.getReceiverName() + "'");
				if (receiverId <= 0) {
					ExtResponse.error(resp, "发送失败:该用户不存在!", "xml");
					return null;
				}
				message.setReceiverId(new Long(receiverId));
			} else if (message.getTypeId() == Message.TYPE_SYSTEM_NOTICE) {
				// 平台通知
				message.setReceiverId(0L);
				message.setReceiverName("全体会员");
				message.setSenderId(0L);
				message.setSenderName("管理员");
			} else if (message.getTypeId() == Message.TYPE_SYSTEM_ANSWER) {
				Message mg0 = (Message) HibernateTemple.load(Message.class,
						message.getTopId());
				if (mg0 != null) {
					mg0.setIsReply(1);
					HibernateTemple.update(mg0);
				}
				message.setReplyDate(new Date());
			}
			message.setCreateDate(new Date());
			HibernateTemple.save(message);
			// 更新通知提示
			Member m = (Member) HibernateTemple.load(Member.class, Integer
					.parseInt("" + message.getReceiverId()));
			if (message.getTypeId() != Message.TYPE_SYSTEM_ASK) {
				new Alert()
						.save(m, "您有新的消息", "您有新消息，来自" + message.getSenderName()
								+ "\n" + message.getContent());
			}
			ExtResponse.ok(resp, "发送成功!", "xml");
		} else if (BankAccountConfig.class.getName().equals(classPath)) {
			HibernateTemple.save(rechargeBank);
		} else if (UnionBuySet.class.getName().equals(classPath)) {
			Member m = (Member) HibernateTemple.load(Member.class, Integer
					.parseInt("" + unionSet.getInitiatorId()));
			double betAmount = unionSet.getPartPrice()
					* unionSet.getInitiatorBuyCount();
			// 检查账户余额
			if (m.getBalance() < betAmount) { // 账户余额不足
				ExtResponse.error(resp, "发起合买失败：账户余额不足!", "xml");
				return null;
			}
			// 更新账户余额
			m.setBalance(m.getBalance() - betAmount);
			HibernateTemple.update(m);

			// 填充数据
			Calendar c = Calendar.getInstance();
			int year = c.get(Calendar.YEAR);
			int month = c.get(Calendar.MONTH); // 一月份则返回0,在返回值上加1为实际月份
			month++;
			int day = c.get(Calendar.DAY_OF_MONTH);
			int hour = c.get(Calendar.HOUR_OF_DAY);
			int minute = c.get(Calendar.MINUTE);
			int second = c.get(Calendar.SECOND);
			int totalTime = hour * 3600 + minute * 60 + second;
			if (totalTime >= TimeHelper.getSecondsByTime("20:30:00")) {
				day++;
				if (month == 2 && day > 28) {
					month = 3;
					day = 1;
				} else if ((month == 4 || month == 6 || month == 9 || month == 11)
						&& day > 30) {
					day = 1;
					month++;
				} else if ((month == 1 || month == 3 || month == 5
						|| month == 7 || month == 8 || month == 10 || month == 12)
						&& day > 31) {
					day = 1;
					month++;
				}
			}

			br.setOrderId(RandomUtil.getRandomString(18));
			br.setCreateDate(new Date());
			Long brId = HibernateTemple.save(br);
			unionSet.setBetId(brId);
			unionSet.setOrderId(br.getOrderId());
			unionSet.setCreateDate(new Date());
			unionSet.setTotalPaidAmount(unionSet.getTotalPaidAmount()
					+ betAmount);
			// 截止日期
			try {
				unionSet.setDealine(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
						.parse(year + "-" + month + "-" + day + " 20:00:00"));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Long unionSetId = HibernateTemple.save(unionSet);
			// 处理合买发起人自身的合买订单
			// 创建合买记录
			UnionBuyRecord unionRecord = new UnionBuyRecord();
			unionRecord.setCreateDate(new Date());
			unionRecord.setOrderId(br.getOrderId());
			unionRecord.setOwnerId(new Long(br.getOwnerId()));
			unionRecord.setBetId(brId);
			unionRecord.setOwnerName(br.getOwnerName());
			unionRecord.setPartPrice(unionSet.getPartPrice());
			unionRecord.setUnionSetId(unionSetId);
			unionRecord.setBuyCount(unionSet.getInitiatorBuyCount());
			// 账变记录
			AccountRecord ar = new AccountRecord();
			ar.setAmountOut(-betAmount);
			ar.setBalance(m.getBalance());
			ar.setCreateDate(new Date());
			ar.setGroupId(AccountRecord.GROUP_LOTTERY_UNION_BET);
			ar.setNote("合买投注");
			ar.setOrderId(br.getOrderId());
			ar.setOwnerId(new Long(br.getOwnerId()));
			ar.setOwnerName(br.getOwnerName());
			ar.setType(AccountRecord.EXPENDITURE);
			/*
			 * MemberStatistics mts = (MemberStatistics)
			 * jdbc.getEntityBySQL(MemberStatistics.class.getName(),
			 * "select * from MemberStatistics where ownerId="+ar.getOwnerId());
			 * mts.setTotalBetAmount(mts.getTotalBetAmount()+betAmount);
			 * mts.setTotalWinAmount(mts.getTotalWinAmount()-betAmount);
			 * HibernateTemple.update(mts);
			 */
			// 更新数据库
			HibernateTemple.save(unionRecord);
			HibernateTemple.save(ar);

			ExtResponse.ok(resp, "发起合买成功!", "xml");
		} else if (UnionBuyRecord.class.getName().equals(classPath)) {
			Member m = (Member) HibernateTemple.load(Member.class, Integer
					.parseInt("" + unionRecord.getOwnerId()));
			UnionBuySet set = (UnionBuySet) HibernateTemple.load(
					UnionBuySet.class, unionRecord.getUnionSetId());
			double betAmount = unionRecord.getPartPrice()
					* unionRecord.getBuyCount();
			// 检查是否截止
			if (new Date().getTime() > set.getDealine().getTime()) {
				ExtResponse.error(resp, "跟单失败：截止时间已过!", "xml");
				return null;
			}
			// 检查账户余额
			if (m.getBalance() < betAmount) { // 账户余额不足
				ExtResponse.error(resp, "跟单失败：账户余额不足!", "xml");
				return null;
			}
			// 更新账户余额
			m.setBalance(m.getBalance() - betAmount);
			HibernateTemple.update(m);

			set.setTotalPaidAmount(set.getTotalPaidAmount() + betAmount);
			HibernateTemple.update(set); // 更新已认购额

			unionRecord.setBetId(set.getBetId());
			unionRecord.setOrderId(set.getOrderId());
			unionRecord.setCreateDate(new Date());
			HibernateTemple.save(unionRecord);

			// 账变记录
			new AccountRecord().insert(m, set.getOrderId(),
					AccountRecord.GROUP_LOTTERY_UNION_BET, -betAmount, "合买投注");

			// 账户统计
			/*
			 * MemberStatistics mts = (MemberStatistics)
			 * jdbc.getEntityBySQL(MemberStatistics.class.getName(),
			 * "select * from MemberStatistics where ownerId="+m.getId());
			 * mts.setTotalBetAmount(mts.getTotalBetAmount()+betAmount);
			 * mts.setTotalWinAmount(mts.getTotalWinAmount()-betAmount);
			 * HibernateTemple.update(mts);
			 */
			ExtResponse.ok(resp, "发起合买成功!", "xml");
		}
		return null;
	}

	public Message getMessage() {
		return message;
	}

	public void setMessage(Message message) {
		this.message = message;
	}

	public Notice getNotice() {
		return notice;
	}

	public void setNotice(Notice notice) {
		this.notice = notice;
	}

	public String getClassPath() {
		return classPath;
	}

	public void setClassPath(String classPath) {
		this.classPath = classPath;
	}

	public void setServletRequest(HttpServletRequest req) {
		// TODO Auto-generated method stub
		this.req = req;
	}

	public BetwayManage getBetwayMg() {
		return betwayMg;
	}

	public void setBetwayMg(BetwayManage betwayMg) {
		this.betwayMg = betwayMg;
	}

	public void setBankdp(BankDeposit bankdp) {
		this.bankdp = bankdp;
	}

	public BankDeposit getBankdp() {
		return bankdp;
	}

	public void setOpenNumber(OpenRewardNumber openNumber) {
		this.openNumber = openNumber;
	}

	public OpenRewardNumber getOpenNumber() {
		return openNumber;
	}

	public void setBr(BetRecord br) {
		this.br = br;
	}

	public BetRecord getBr() {
		return br;
	}

	public void setWr(WithdrawRecord wr) {
		this.wr = wr;
	}

	public WithdrawRecord getWr() {
		return wr;
	}

	public void setExt1(String ext1) {
		this.ext1 = ext1;
	}

	public String getExt1() {
		return ext1;
	}

	public void setExt2(String ext2) {
		this.ext2 = ext2;
	}

	public String getExt2() {
		return ext2;
	}

	public void setServletResponse(HttpServletResponse resp) {
		// TODO Auto-generated method stub
		this.resp = resp;
	}

	public void setBetway(BetWay betway) {
		this.betway = betway;
	}

	public BetWay getBetway() {
		return betway;
	}

	public void setRechargeBank(BankAccountConfig rechargeBank) {
		this.rechargeBank = rechargeBank;
	}

	public BankAccountConfig getRechargeBank() {
		return rechargeBank;
	}

	public void setUnionSet(UnionBuySet unionSet) {
		this.unionSet = unionSet;
	}

	public UnionBuySet getUnionSet() {
		return unionSet;
	}

	public void setUnionRecord(UnionBuyRecord unionRecord) {
		this.unionRecord = unionRecord;
	}

	public UnionBuyRecord getUnionRecord() {
		return unionRecord;
	}

	public void setReward(double reward) {
		this.reward = reward;
	}

	public double getReward() {
		return reward;
	}
}
